<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/11/26
 * Time: 21:09
 */

namespace app\storage\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;

class BomModel extends Model
{
    protected $table = 'iwh_bom';
    protected $pk = 'uuid';


    public function Storage()
    {
        return $this->belongsTo('StorageModel', 'storage_uuid', 'uuid')->bind(['storage_name' => 'name']);
    }

    public function Supplier()
    {
        return $this->belongsTo('SupplierModel', 'supplier_uuid', 'uuid', '', 'left')->bind(['company_name','supplier_type'=>'type']);
    }

    public function BomDetail(){
        return $this->hasMany('BomDetailModel','bom_uuid','uuid');
    }

    /**
     * 根据条件获取bom的数据
     *
     * @param $condition
     * @return false|\PDOStatement|string|\think\Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     */
    public function getBom($condition)
    {

        $storageUuid = $condition['where']['storage_uuid'];//这段代码比较复杂，经过不断修改以后几乎变成了一个黑盒。
        //如果为admin的话，storageUuid即为 in [所有的仓库的uuid的集合]
        unset($condition['where']['storage_uuid']);
        $where = $condition['where'];
        $pageIndex = $condition['pageIndex'];
        $pageSize = $condition['pageSize'];
        if (!empty($where['company_name'])) {
            $where['b.company_name'] = $where['company_name'];
            unset($where['company_name']);
        }
        if (!empty($where['storage_name'])) {
            $where['c.name'] = $where['storage_name'];
            unset($where['storage_name']);
        }

        $result['total'] = $this->alias('a')
            ->join(['iwh_supplier'=>'b'], 'b.uuid = a.supplier_uuid','left')
            ->join(['iwh_storage'=>'c'],'c.uuid = a.storage_uuid','left')

            ->where(function($query) use($storageUuid){
                $query->where('storage_uuid',$storageUuid)
                    ->whereOr('storage_uuid' ,NULL)//确保能够查出仓库字段为空的值
                    ->whereOr('storage_uuid','');//确保能够查出
            })
            ->where($where)
            ->count();

        $result['row'] = $this->alias('a')->field('a.*,b.company_name,c.name')
            ->join(['iwh_supplier'=>'b'], 'b.uuid = a.supplier_uuid','left')
            ->join(['iwh_storage'=>'c'],'c.uuid = a.storage_uuid','left')
            ->order('time desc')
            ->page($pageIndex, $pageSize)

            ->where(function($query) use($storageUuid){
                $query->where('storage_uuid',$storageUuid)
                    ->whereOr('storage_uuid',NULL)
                    ->whereOr('storage_uuid','');
            })
            ->where($where)
//            ->fetchSql()
        ->select()->toArray();

        return $result;
    }

    public function deleteBom($bomUuid){
        $status = $this->where('uuid', $bomUuid)->value('status');
        if ($status !== 0) {
            return ret_template(false, '该订单已出库不允许删除');
        }

        $bomDetailModel = new BomDetailModel();
        $this->startTrans();

        $result2 = $bomDetailModel->where(['bom_uuid'=>$bomUuid])->delete();
        $storageModel = new StorageModel();
        $isOutput = $storageModel->where(['bom_uuid'=>$bomUuid])->value('uuid');
        $isOutflow = $this->getBomOutflowByUuid($bomUuid);
        $result3 = true;
        $result1 = $this->where(['uuid'=>$bomUuid])->delete();
        //如果是正常出库的订单且没有流水允许删除，以便PDA可以顺利退出
        if($isOutput && empty($isOutflow)){
            $result3 =  $storageModel->where('uuid',$isOutput)->update(['bom_uuid'=>'']);
        }
        if($result1 && $result2 !== false && $result3){
            $this->commit();
            return ret_template(true, '订单删除成功');
        }else{
            $this->rollback();
            return ret_template(false, '订单删除失败');
        }
    }

    public function getBomOutflowByUuid($uuid){
        $bomInfo = $this->field('order_id,fentryid')->where('uuid',$uuid)->find()->toArray();
        $outFlowModel = new OutflowModel();
        $outflow = $outFlowModel->where($bomInfo)->select();
        $outflow = count($outflow)?$outflow->toArray():[];
        return $outflow;
    }
}